<template>
    <div>
        <van-tabs class="van-tabs" v-model="active" color="#EE421B" title-active-color="#EE421B" @click="getTitle">
            <!-- 二级菜单 -->
            <div class="sub-menus" v-show="active < 4 && secondMenu.length">
                <div :class="['sub-menu', activeMenu == index ? 'sub-menu-active' : '']" v-for="(item, index) in secondMenu"
                    :key="index" @click="selectMenu(index, item.laneId, item)">{{
                        item.tabName }}</div>
            </div>
            <van-tab title="精选" line-width="40px">
                <videoList v-if="videoList.length" :videoResultList="videoList" @getNextPage="getChoicenessVideo"
                    :listFinished="finished" :listLoading="loading" @fromVideoListInfo="fromVideoListData"></videoList>
                <div class="empty-page" v-else><img src="../../assets/images/zxjt/empty-page1.png" alt=""></div>
            </van-tab>
            <van-tab title="优选公募" line-width="40px">
                <videoList v-if="videoList.length" :videoResultList="videoList" :listFinished="finished"
                    :listLoading="loading" @fromVideoListInfo="fromVideoListData"></videoList>
                <div class="empty-page" v-else><img src="../../assets/images/zxjt/empty-page1.png" alt=""></div>
            </van-tab>
            <van-tab title="高端专区" line-width="40px">
                <videoList v-if="videoList.length" :videoResultList="videoList" :listFinished="finished"
                    :listLoading="loading" @fromVideoListInfo="fromVideoListData"></videoList>
                <div class="empty-page" v-else><img src="../../assets/images/zxjt/empty-page1.png" alt=""></div>
            </van-tab>
            <van-tab title="产品小课堂" line-width="40px">
                <videoList v-if="videoList.length" :videoResultList="videoList" :listFinished="finished"
                    :listLoading="loading" @fromVideoListInfo="fromVideoListData"></videoList>
                <div class="empty-page" v-else><img src="../../assets/images/zxjt/empty-page1.png" alt=""></div>
            </van-tab>
            <van-tab class="special-column-video" title="精品专栏" line-width="40px">
                <div v-if="secondMenu.length">
                    <div class="special-video-detial" v-for="(item, index) in secondMenu" :key="index"
                        @click="goPubSel(item)">
                        <img :src="item.pictureUrl + '?x-oss-process=image/resize,m_fixed,h_317,w_500'">
                        <div class="special-video-info">
                            <div class="title">{{ item.tabName }}</div>
                            <div class="time">{{ item.createdTime }}</div>
                        </div>
                    </div>
                </div>
                <div v-else class="empty-page"><img src="../../assets/images/zxjt/empty-page1.png" alt=""></div>
            </van-tab>
            <van-tab class="live-station" title="直播小站" line-width="40px">
                <van-list v-if="liveVideo.length" v-model="loading" :finished="finished" finished-text="到底啦" @load="getLiveVideo"
                    :immediate-check="false" :offset="50">
                    <div class="live-station-detial" v-for="(item, index) in liveVideo" :key="index"
                        @click="goLiveRoom(item.type, item.roomId)">
                        <img :src="item.coverUrl + '?x-oss-process=image/resize,m_fixed,h_317,w_698'">
                        <div class="live" v-if="item.type == 1">
                            <div class="status">直播中</div>
                            <div class="status-detial">{{ item.roomMember }}人</div>
                        </div>
                        <div class="play-back" v-else-if="item.type == 3">
                            <div class="status">回放</div>
                        </div>
                        <div class="advance" v-else>
                            <div class="status">预告</div>
                            <div class="status-detial">{{ item.beginTime | formatTime }}</div>
                        </div>
                        <div class="live-station-info">
                            <div class="title">{{ item.contentTitle }}</div>
                            <div class="live-info">
                                <div class="author">
                                    <div class="tag">{{ item.tagName }}</div>
                                    <div class="name">{{ item.author }}</div>
                                </div>
                                <div class="time" v-if="item.type == 3">{{ item.beginTime | formatTime }}</div>
                            </div>
                        </div>
                    </div>
                </van-list>
                <div v-else class="empty-page"><img src="../../assets/images/zxjt/empty-page1.png" alt=""></div>
            </van-tab>
        </van-tabs>
    </div>
</template>

<script>
import videoList from '../compoments/videoList.vue'
import { getRecommendData, getVideoCollectMost, getVideoWatchMost, getLiveStation } from '../../util/api'
export default {
    props: ['allMenu'],
    components: {
        videoList
    },
    data() {
        return {
            active: 0,
            choicenessSecondMenu: [
                // { tabName: '推荐', laneId: 0 },
                { tabName: '收藏最多', choiceness: 1, laneId: 1 },
                { tabName: '观看最多', choiceness: 1, laneId: 2 }],//精选的二级菜单是固定的
            activeMenu: 0,//用于改变样式
            videoList: [],
            liveVideo: [],
            laneId: '',//推荐位代码
            collectOrWacthId: '',//用于区分 收藏最多  观看最多  直播小站  收藏最多：1 观看最多：2  直播小站：3
            page: 1,//页码
            pageSize: 10,
            finished: false,
            loading: false,
            liveType: "1,2",//先查直播和预告，再查回看
            tagId: '8', //视频专区指定标签Id
            secTabName:''//当前活动的二级菜单，用于打点
        }
    },
    methods: {
        selectMenu(index, laneId, item) {
            this.secTabName = this.secondMenu[index] && this.secondMenu[index].tabName
            this.videoList = []//每次点击后要把上次的数据清空
            this.liveVideo = []
            this.page = 1//重置页数
            this.finished = false//重置下拉刷新
            this.activeMenu = index//修改样式
            this.laneId = laneId//
            this.collectOrWacthId = laneId//用于区分 收藏最多 观看最多
            if (item && item.choiceness) {//如果是 收藏最多 观看最多 调另外的接口
                this.getChoicenessVideo()
                this.secTabDot(this.secTabName)//二级菜单打点
            } else if(laneId == 1){//首页精选没有收藏和观看以外的二级菜单
                this.getChoicenessVideo()
                this.secTabDot(this.secTabName)//二级菜单打点
            }else if (laneId == 3) {
                //获取直播小站信息
                this.getLiveVideo()
            } else {
                //点击请求推荐位接口获取视频信息()
                this.getVideo()
                this.secTabDot(this.secTabName)//二级菜单打点
            }

        },
        //去专栏详细页
        goPubSel(item) {
            // this.$router.push(livmRoom/roomid?type)
            const params = {
                path: '/zxjt/publicSelection',
                query: {
                    tabId: item.tabId,
                    laneId: item.laneId,
                    dzhPage: 'true'
                }
            }
            this.colDot(item.tabName)//点击专栏打点
            this.colDotClick(item.tabName)
            this.$router.push(params)
        },
        //去看回放或者直播间
        goLiveRoom(status, id) {
            let params = {}
            //回放
            if (status == 3) {
                params = {
                    path: `/${this.$channel}/liveBack/${id}`,
                    query: {
                        liveStation: '1',
                        dzhPage:'true'
                    }
                }
            } else {
                // 直播/预告
                params = {
                    path: `/${this.$channel}/liveRoom/${id}`,
                    query: {
                        liveStation: '1',
                        dzhPage: 'true'
                    }
                }
            }
            this.$router.push(params)
        },
        // 点击一级、二级获取相应的视频数据（推荐位接口无分页）
        async getVideo() {
            const videoParams = {
                "userId": "1776083031124",//手机号（如果未登录，给一个固定的uuid用于请求判重）
                "mode": "11",// 默认11
                "deviceId": "xiaomi-12-1",//设备号
                "isNewIn": 1,//是否首屏（首屏1 非首屏 0）
                "laneCode": this.laneId,//推荐位代码
                "appVer": "8.8.0",//版本号
                "appType": "android"//App类型
            }
            this.loading = true
            try {
                const dataMsg = await getRecommendData(videoParams);
                const { code, data } = dataMsg.data
                if (code === '000000') {
                    if (data.items.length) {
                        data.items.forEach(e => {
                            this.videoList.push({
                                coverUrl: e.coverUrl,
                                duration: e.hzbVideo.duration,//视频时长
                                contentTitle: e.contentTitle,
                                author: e.orgName,
                                tagName: e.tags[0] && e.tags[0].tagName,
                                h5Url: e.h5Url,
                                videoLiveId: e.videoLiveId,//用于埋点
                                mainId: e.mainId || '',//用于埋点
                                videoId:e.videoId || ''
                            })
                        });
                    }
                    //请求一次就没有数据了，因为没有分页
                    this.finished = true
                    this.loading = false
                }
            } catch (error) {
                console.log('error');
                this.finished = true
                this.loading = false
            }

        },
        //点击 收藏最多 观看最多(分页)
        getChoicenessVideo() {
            if (this.collectOrWacthId == 1) {
                this.getCollectVideo()
            } else {
                this.getWatchVideo()
            }

        },
        //获取收藏最多(分页)
        async getCollectVideo() {
            try {
                this.loading = true
                const dataMsg = await getVideoCollectMost(this.page, this.pageSize)
                const { code, data } = dataMsg.data
                if (code == '000000') {
                    data.forEach(item => {
                        this.videoList.push({
                            coverUrl: item.imagUrl,
                            duration: item.duration,//视频时长
                            contentTitle: item.title,
                            author: item.roomVideoExt2.corpName,
                            // tagName: item.tags ? item.tags[0].tagName : '',//标签
                            tagName: item.labels && item.labels.split("|")[0],//标签
                            h5Url: item.video,
                            id: item.id,//回放id
                            videoLiveId: item.id//用于埋点
                        })
                    })
                    console.log(data);
                    this.page++
                    this.loading = false
                    //判断是不是最后一页
                    if (data.length < 10) {
                        console.log('关');
                        this.finished = true
                    }
                }
            } catch (error) {
                console.log(error);
                //显示加载完成
                this.finished = true
                this.loading = false
            }
        },
        //获取观看最多(分页)
        async getWatchVideo() {
            try {
                this.loading = true
                const dataMsg = await getVideoWatchMost(this.page, this.pageSize)
                const { code, data } = dataMsg.data
                if (code == '000000') {
                    data.forEach(item => {
                        this.videoList.push({
                            coverUrl: item.imagUrl,
                            duration: e.duration,//视频时长
                            contentTitle: item.title,
                            author: item.roomVideoExt2.corpName,
                            // tagName: item.tags ? item.tags[0].tagName : '',//标签
                            tagName: item.labels && item.labels.split(",")[0],//标签
                            h5Url: item.video,
                            id: item.id,//回放id
                            videoLiveId: item.id//用于埋点
                        })
                    })
                    console.log(data);
                    this.page++
                    this.loading = false
                    //判断是不是最后一页
                    if (data.length < 10) {
                        console.log('关');
                        this.finished = true
                    }
                }
            } catch (error) {
                console.log(error);
            }
        },
        //获取直播小站信息（分页）
        async getLiveVideo() {
            try {
                this.loading = true
                const dataMsg = await getLiveStation(this.liveType, this.tagId, this.page, this.pageSize)
                // const dataMsg = await getLiveStation(4, 273, this.page, this.pageSize)
                const { code, data } = dataMsg.data
                if (code == '000000') {
                    data.forEach(item => {
                        this.liveVideo.push({
                            coverUrl: item.imgUrl,//封面
                            beginTime: item.beginTime,//直播开始时间（预告）或者是回放生成时间
                            nickName: item.nickName,//名字
                            roomMember: item.roomMember,//直播间人数
                            type: item.type,//直播状态  1直播中 2 预告 3 回放
                            contentTitle: item.title,//视频title
                            videoUrl: item.videoUrl,//视频跳转url
                            tagName: item.tags[0] ? item.tags[0].tagName : "",//tag
                            author: item.nickName,//主播名字
                            roomId: item.mixId//直播间Id
                        })
                    })
                    console.log(data);
                    this.page++
                    this.loading = false
                    //判断是不是最后一页
                    if (data.length < 10 && this.liveType == "1,2") {
                        this.liveType = "3"
                        this.page = 1//重置页码
                        this.getLiveVideo()
                    } else if (data.length <= 10 && this.liveType == "3") {
                        this.finished = true
                    }
                }
            } catch (error) {
                console.log(error);
            }
        },
        //点击首页Tab打点
        getTitle(name,title) {
            $sensorsTrack('financing_videoZoneTabClick', {
                page_name:'首页',
                tab_name:title
            });
        },
        //点击二级模块打点
        secTabDot(functionName) {
            if(!functionName) return
            $sensorsTrack('financing_videoZoneFunctionClick', {
                page_name: '首页',
                module_name: this.firstMenu[this.active],
                function_name: functionName
            });
        },
        //点击专栏打点(二级菜单)
        colDot(columnName) {
            $sensorsTrack('financing_videoZoneFunctionClick', {
                page_name: '首页',
                module_name:'精品专栏',
                column_name: columnName,
            });
        },
        //点击专栏打点（专栏点击）
        colDotClick(columnName){
            $sensorsTrack('financing_videoZoneColumnClick', {
                page_name: '首页',
                column_name: columnName,
            });
        },
        //视频打点
        clickVideoDot(mainId, video_id, video_name) {
            $sensorsTrack('financing_videoZoneVideoClick', {
                page_name: '首页',
                module_name: this.firstMenu[this.active],
                secondary_module: this.secTabName,
                main_id: mainId? mainId:'',
                video_id: video_id,
                video_name: video_name
            });
        },
        //视频打点(曝光)
        exposureVideoDot(mainId, video_id, video_name) {
            $sensorsTrack('financing_videoZoneVideoExposure', {
                page_name: '首页',
                module_name: this.firstMenu[this.active],
                secondary_module: this.secTabName,
                main_id: mainId ? mainId : '',
                video_id: video_id,
                video_name: video_name
            });
        },
        fromVideoListData(vlData) {
            if (vlData.type == 'click') {
                this.clickVideoDot(vlData.mainId, vlData.videoLiveId, vlData.title)
            } else {
                this.exposureVideoDot(vlData.mainId, vlData.videoLiveId, vlData.title)
            }
        }
    },
    computed: {
        //筛选所有一级菜单
        firstMenu() {
            let arr = []
            arr = this.allMenu.filter((item) => {
                //去除banner和card
                if (item.level == 1 && item.tabId <= 5) return item
            })
            arr.push({
                "tabId": 1,
                "laneId": 3,
                "tabName": "直播小站",
                "level": 1,
                "parentId": null,
            })
            return arr
        },
        //栏目的二级菜单(当tab为精品专栏时以卡片形式显示,tab为精选时是固定二级菜单)
        secondMenu() {
            if (this.active == 0) {
                //当一级菜单为精选时，筛选唯一的二级菜单加到收藏和观看最多前面
                let arr = this.allMenu.filter((item) => {
                    if (item.parentId == this.active + 1) return item
                })
                return [...arr,...this.choicenessSecondMenu]
            } else {
                return this.allMenu.filter((item) => {
                    if (item.parentId == this.active + 1) return item
                })
            }

        },
    },
    filters: {
        formatTime(time) {
            let date = time.split(" ")
            let d = date[0]
            let t = date[1]
            let day = d.split("-")
            let clock = t.split(":")
            return day[1] + '月' + day[2] + '日' + ' ' + clock[0] + ":" + clock[1]
        }
    },
    watch: {
        //监听active，只要一变化就调推荐位接口，并整理一级菜单的laneId作为参数
        active(newValue) {
            this.liveType = "1,2"//重置直播小站类型
            //精品专栏和直播小站不需要请求第一个二级菜单
            if (newValue == 5) {
                this.laneId = this.firstMenu[newValue].laneId
                this.selectMenu(0, this.laneId)               
            } else if (newValue == 4) {
                return
            } else {
                this.laneId = this.secondMenu.length && this.secondMenu[0].laneId
                this.selectMenu(0, this.laneId)
            }
            console.log(newValue);
        },
        //菜单一传进来就立刻请求一次精选页
        allMenu:{
            handler(){
                this.laneId = this.secondMenu[0].laneId
                this.secTabName = this.secondMenu[0].tabName
                this.selectMenu(0, this.laneId)
            },
        }
    }
}
</script>

<style scoped lang="less">
.van-tabs {
    margin-top: 36px;

    .sub-menus {
        width: 100%;
        height: 65px;
        white-space: nowrap;
        overflow-x: scroll;
        padding-top: 10px;
        .sub-menu {
            height: 100%;
            width: auto;
            display: inline;
            line-height: 41.6px;
            background-color: rgba(245, 246, 249, 1);
            border-radius: 50px;
            padding: 12px 35px;
            margin-right: 30px;
            color: #757E93;
        }

        .sub-menu-active {
            background-color: rgba(255, 90, 0, 0.05);
            color: #FF5A00;
        }
    }

    .special-column-video,
    .live-station {

        .special-video-detial,
        .live-station-detial {
            width: 100%;
            height: 454px;
            border-radius: 20px;
            margin-bottom: 20px;
            box-shadow: 0px 4px 8px #EFEFEF;
            position: relative;

            img {
                width: 100%;
                height: 317px;
                border-radius: 20px 20px 0 0;
            }

            .live,
            .play-back,
            .advance {
                position: absolute;
                top: 11px;
                left: 11px;
                border-radius: 7px;
                display: flex;
                justify-content: space-between;

                .status {
                    height: 100%;
                    width: 100px;
                    border-radius: 7px;
                    color: #ffffff;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-size: 25px;
                }

                .status-detial {
                    flex: 1;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-size: 25px;
                    color: #ffffff;
                }
            }

            .live {
                width: 231px;
                height: 43px;
                background-color: rgba(238, 66, 27, 0.4);

                .status {
                    background-color: rgba(238, 66, 27, 1);
                }
            }

            .play-back {
                width: 231px;
                height: 43px;

                .status {
                    background-color: rgba(245, 133, 27, 1);
                }
            }

            .advance {
                width: 318px;
                height: 43px;
                background-color: rgba(83, 121, 225, 0.4);

                .status {
                    background-color: rgba(83, 121, 225, 1);
                }
            }

            .special-video-info,
            .live-station-info {
                position: absolute;
                bottom: 0;
                left: 0;
                width: 100%;
                height: 137px;
                border-radius: 0 0 20px 20px;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                padding: 19px;

                .title {
                    color: #262E40;
                    font-size: 28px;
                    font-weight: 600;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }

            .special-video-info {
                .time {
                    font-size: 26px;
                    color: #9AA2B3;
                }
            }

            .live-station-info {
                .live-info {
                    display: flex;
                    justify-content: space-between;

                    .title {
                        font-size: 26px;
                        color: #9AA2B3;
                    }

                    .author {
                        display: flex;

                        .tag {
                            width: 108px;
                            height: 36px;
                            background-color: #FEE4B0;
                            font-size: 22px;
                            line-height: 35px;
                            text-align: center;
                            border-radius: 12px 5px;
                            color: #B67531;
                            font-weight: 400;
                        }

                        .name {
                            padding-left: 9px;
                            font-size: 24px;
                            font-weight: 400;
                            line-height: 36px;
                            color: #50596D;
                        }
                    }
                }

            }
        }

        .empty-page {
            width: 490px;
            height: 417px;
            margin: 99px auto;

            img {
                width: 100%;
                height: 100%;
                margin-bottom: 99px;
            }
        }
    }

    .empty-page {
        width: 490px;
        height: 417px;
        margin: 99px auto;

        img {
            width: 100%;
            height: 100%;
            margin-bottom: 99px;
        }
    }
}

/deep/ .van-tab {
    font-size: 30px;
    font-weight: 400;
    color: #262E40;
    white-space: nowrap;
}

/deep/ .van-tabs__line {
    width: 30px;
    height: 6px;
    border-radius: 30%;
    margin-top: 16px;
}

/deep/ .van-tabs--line .van-tabs__wrap {
    height: 2.375rem;
    margin-bottom: 19px;
    margin-left: -20px;
}

.special-column-video,
.live-station {

    /deep/ .van-list__finished-text {
        font-size: 25px;
    }

    /deep/ .van-loading__text {
        font-size: 25px;
    }
}</style>